#include "print_tree.h"
#include <stdio.h>

// 打印数字
static void _print_number(i32_s num) {
	if (num < 0) {
		putchar('(');
	}
	printf("%d", num);
	if (num < 0) {
		putchar(')');
	}
}

typedef struct {
	u32_s ch;
	b32_s is_mul_div;
} oper_ch_is_add_sub_t;

static oper_ch_is_add_sub_t _get_oper_ch_is_add_sub(oper_e oper) {
	oper_ch_is_add_sub_t result;
	oper_dmd_s dmd = oper_get_dmd(oper);
	result.is_mul_div = dmd.is_mul_div;
	switch (oper) {
	case OPER_ADD:
		result.ch = '+';
		break;

	case OPER_SUB:
		result.ch = '-';
		break;

	case OPER_MUL:
		result.ch = '*';
		break;

	case OPER_DIV:
		result.ch = '/';
		break;

		// 理论上不可能default
	default:
		break;
	}
	return result;
}

static void _print_subtree(const tree34_t* tree_p, const node_t* node_p,
			   b32_s may_bracket) {
	// 如果根结点是数字，简单处理后直接结束。
	if (!node_is_oper(tree_p, node_p)) {
		i32_s num = node_get_num(tree_p, node_p);
		_print_number(num);
		return;
	}

	oper_e oper = node_get_oper(tree_p, node_p);
	oper_ch_is_add_sub_t oper_ch_is_mul_div = _get_oper_ch_is_add_sub(oper);
	u32_s ch = oper_ch_is_mul_div.ch;
	u32_s is_mul_div = oper_ch_is_mul_div.is_mul_div;
	u32_s need_bracket = (may_bracket && !is_mul_div);
	if (need_bracket) {
		putchar('(');
	}
	sub_nodes_t sub = node_get_sub(tree_p, node_p);
	_print_subtree(tree_p, sub.left_p, is_mul_div);
	putchar(' ');
	putchar(ch);
	putchar(' ');
	_print_subtree(tree_p, sub.right_p, is_mul_div);
	if (need_bracket) {
		putchar(')');
	}
}

// 暂时使用运算符前置的方式输出算式
void print_tree(const tree34_t* tree_p) {
	const node_t* node_p = tree_get_head(tree_p);
	_print_subtree(tree_p, node_p, 0);
	puts(" = 24");
}
